package Top;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lwg
 * @Date: 2021/6/17 20:31
 * @Description: 两数相加(两个链表相加)
 */
public class test2 {
    public  ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       /* //1.初始化合并的列表
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        //2.定义进位值
        int carry = 0;
        //3.得到循环条件
        while (l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            //4.得到两链表的和
            int sum = x + y + carry;
            //5.得到进位值以及进位后剩下的和
            carry = sum > 9 ? 1 : 0;
            sum = sum % 10;
            //6.将和放到新的链表中
            cur.next=new ListNode(sum);
            cur=cur.next;

            //7.将l1,l2链表继续往下遍历
            if (l1.next!=null){
                l1=l1.next;
            }
            if (l2.next!=null){
                l2=l2.next;
            }
        }
        //判断最后一次相加是否进位，进位加入新链表
        if (carry==1){
            cur.next=new ListNode(carry);
        }
        //返回除了前驱节点的链表
        return cur.next;*/

        /**
         *  @author: lwg
         *  @Date: 2021/6/15 12:48
         *  @Description: 方法二
         */
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int x = l1 != null ? l1.val : 0;
            int y = l2 != null ? l2.val : 0;
            int sum = x + y + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail=tail.next;
            }
            carry = sum / 10;
            if (l1!=null){
                l1=l1.next;
            }
            if (l2!=null){
                l2=l2.next;
            }
        }
        if (carry>0){
            tail.next=new ListNode(carry);
        }
        return head;
    }


}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }


}
